package thread.threadlocal;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import org.omg.CORBA.CurrentHolder;
/**
 * 另一个threadlocal实现方式，就必须保证map的安全性了，而且要考虑线程销毁后，map不释放key的问题
 * 这样的map属于全局级别的，会冲突,而且这样的实现方法好像是1.3以前的方法
 * @author Han
 */
public class MyThreadLocalDemo {
	private static Map<Thread,String> map = new ConcurrentHashMap<Thread,String>();
	private static String contextStr = "";
	public static void set(String str){
		Thread t = Thread.currentThread();
		//System.out.println(map.containsKey(t));
		//synchronized (map) {
		//这里出错的原因一定是因为map是线程不安全的。至于为什么。不知道了。
		//http://blog.csdn.net/jiafu1115/article/details/7574350
		System.out.println(map.put(t, str));
		//}
		//System.out.println(t); 
		System.out.println(map.keySet());
	}
	
	public static String get(){
		return map.get(Thread.currentThread());
	}
	
	public static String getStr(){
		return contextStr;
	}
	public static void setStr(String str){
		contextStr = str;
	}
	
	public static void print(){
		System.out.println(map);
	}
	
	public static class MyThread extends Thread{
//		public MyThread(String name){
//			super(name);
//		}
		@Override
		public void run() {
			int i = new Random().nextInt(10);
			String str = Thread.currentThread().getId()+","+i;
			MyThreadLocalDemo.set(str);
			MyThreadLocalDemo.setStr(str);
			System.out.println("```threadlocal的值"+str);
			//System.out.println(Thread.currentThread());
			try {
				Thread.currentThread().sleep(500);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println("`threadlocal的值"+MyThreadLocalDemo.get());
			//print();
		}
	}
	
	public static void main(String[] args) {
		//运行以下代码可以看出，两个线程，持有的threadlocal没有因为另一个改变了值而发生改变
//		for(int i = 0;i<20;i++){
//			Thread t1 = new MyThreadLocalDemo().new MyThread();
//			Thread t2 = new MyThreadLocalDemo().new MyThread();
//			t1.start();
//			t2.start();
//		}
		//导致出现null的问题是由于两个线程同城对map进行了初始化。
		//set("c");
		Thread t1 = new MyThreadLocalDemo.MyThread();
		Thread t2 = new MyThreadLocalDemo.MyThread();
		t1.start();
		t2.start();
		//System.out.println(get()+"---");
	}
}
